# -*- coding: utf-8 -*-
"""
羽毛球大赛比赛管理器
负责处理比赛流程、抽签逻辑、晋级规则等
"""

import json
import random
import uuid
from typing import List, Dict, Optional, Tuple
from datetime import datetime


class TournamentManager:
    """比赛管理器"""

    def __init__(self, redis_client=None):
        self.redis_client = redis_client
        self.tournament_key = "badminton:tournament"
        self.config_key = "badminton:tournament_config"

        # 默认比赛配置（如果Redis中没有配置则使用此默认值）
        self.default_config = {
            'total_teams': 10,
            'groups': ['A', 'B', 'C'],
            'rounds': [
                {
                    'name': 'round1_main',
                    'display_name': '第一轮晋级赛',
                    'groups_count': 5,  # 5个对战组
                    'teams_per_group': 2,  # 每组2队
                    'advance_count': 5,  # 晋级5队
                    'type': 'main'  # main: 主要比赛, revival: 复活赛
                },
                {
                    'name': 'round1_revival',
                    'display_name': '复活赛',
                    'groups_count': 3,  # 3个组：2个对战组 + 1个轮空组
                    'teams_per_group': 2,  # 对战组每组2队，轮空组1队
                    'advance_count': 3,  # 复活3队
                    'type': 'revival'
                },
                {
                    'name': 'round2_main',
                    'display_name': '第二轮晋级赛',
                    'groups_count': 4,  # 4个对战组
                    'teams_per_group': 2,  # 每组2队
                    'advance_count': 4,  # 晋级4队
                    'type': 'main'
                },
                {
                    'name': 'round3_main',
                    'display_name': '第三轮晋级赛',
                    'groups_count': 2,  # 2个对战组
                    'teams_per_group': 2,  # 每组2队
                    'advance_count': 2,  # 晋级2队
                    'type': 'main'
                },
                {
                    'name': 'final',
                    'display_name': '决赛',
                    'groups_count': 1,  # 1个对战组
                    'teams_per_group': 2,  # 每组2队
                    'advance_count': 1,  # 冠军1队
                    'type': 'final'
                }
            ]
        }

        # 加载配置
        self.config = self.load_config()

    def load_config(self) -> Dict:
        """从Redis加载配置，如果不存在则使用默认配置"""
        if self.redis_client:
            try:
                config_data = self.redis_client.get(self.config_key)
                if config_data:
                    return json.loads(config_data)
            except Exception as e:
                print(f"加载配置失败: {e}")
        return self.default_config.copy()

    def save_config(self, config: Dict) -> bool:
        """保存配置到Redis"""
        if self.redis_client:
            try:
                self.redis_client.set(self.config_key, json.dumps(config, ensure_ascii=False))
                self.config = config  # 更新内存中的配置
                return True
            except Exception as e:
                print(f"保存配置失败: {e}")
        return False

    def update_config(self, new_config: Dict) -> Tuple[bool, str]:
        """更新比赛配置（管理员操作）"""
        try:
            # 验证配置格式
            if 'total_teams' not in new_config or 'rounds' not in new_config:
                return False, "配置格式错误，缺少必要字段"

            if not isinstance(new_config['rounds'], list) or len(new_config['rounds']) == 0:
                return False, "轮次配置不能为空"

            # 验证每轮配置
            for round_config in new_config['rounds']:
                required_fields = ['name', 'display_name', 'groups_count', 'teams_per_group', 'advance_count', 'type']
                for field in required_fields:
                    if field not in round_config:
                        return False, f"轮次配置缺少字段: {field}"

            if self.save_config(new_config):
                return True, "配置更新成功"
            else:
                return False, "保存配置失败"

        except Exception as e:
            return False, f"更新配置失败: {str(e)}"

    def get_config(self) -> Dict:
        """获取当前配置"""
        return self.config.copy()

    def get_round_config(self, round_name: str) -> Optional[Dict]:
        """获取指定轮次的配置"""
        if not self.config or 'rounds' not in self.config:
            return None
        for round_config in self.config['rounds']:
            if round_config['name'] == round_name:
                return round_config
        return None

    def add_round(self, round_data: Dict) -> Tuple[bool, str]:
        """添加比赛轮次"""
        try:
            # 验证轮次数据格式
            required_fields = ['name', 'display_name', 'groups_count', 'teams_per_group', 'advance_count', 'type']
            for field in required_fields:
                if field not in round_data:
                    return False, f"轮次配置缺少字段: {field}"

            # 检查轮次名称是否重复
            for existing_round in self.config['rounds']:
                if existing_round['name'] == round_data['name']:
                    return False, f"轮次名称 '{round_data['name']}' 已存在"

            # 添加轮次到配置
            self.config['rounds'].append(round_data)

            if self.save_config(self.config):
                return True, "轮次添加成功"
            else:
                return False, "保存配置失败"

        except Exception as e:
            return False, f"添加轮次失败: {str(e)}"

    def update_round(self, round_name: str, round_data: Dict) -> Tuple[bool, str]:
        """修改轮次配置"""
        try:
            # 验证轮次数据格式
            required_fields = ['name', 'display_name', 'groups_count', 'teams_per_group', 'advance_count', 'type']
            for field in required_fields:
                if field not in round_data:
                    return False, f"轮次配置缺少字段: {field}"

            # 查找并更新轮次
            round_found = False
            for i, existing_round in enumerate(self.config['rounds']):
                if existing_round['name'] == round_name:
                    # 如果修改了轮次名称，检查新名称是否重复
                    if round_data['name'] != round_name:
                        for other_round in self.config['rounds']:
                            if other_round['name'] == round_data['name']:
                                return False, f"轮次名称 '{round_data['name']}' 已存在"

                    self.config['rounds'][i] = round_data
                    round_found = True
                    break

            if not round_found:
                return False, f"轮次 '{round_name}' 不存在"

            if self.save_config(self.config):
                return True, "轮次修改成功"
            else:
                return False, "保存配置失败"

        except Exception as e:
            return False, f"修改轮次失败: {str(e)}"

    def delete_round(self, round_name: str) -> Tuple[bool, str]:
        """删除轮次"""
        try:
            # 查找并删除轮次
            round_found = False
            for i, existing_round in enumerate(self.config['rounds']):
                if existing_round['name'] == round_name:
                    self.config['rounds'].pop(i)
                    round_found = True
                    break

            if not round_found:
                return False, f"轮次 '{round_name}' 不存在"

            if self.save_config(self.config):
                return True, "轮次删除成功"
            else:
                return False, "保存配置失败"

        except Exception as e:
            return False, f"删除轮次失败: {str(e)}"

    def set_current_round(self, round_name: str) -> Tuple[bool, Dict, str]:
        """设置当前轮次并开始抽签（只能向前切换到下一轮）"""
        try:
            # 验证轮次是否存在
            round_config = self.get_round_config(round_name)
            if not round_config:
                return False, {}, f"轮次 '{round_name}' 不存在"

            state = self.get_tournament_state()
            if not state:
                return False, {}, "获取比赛状态失败"

            # 读取历史数据并验证轮次切换的合法性
            validation_result = self._validate_round_switch_with_history(state, round_name, round_config)
            if not validation_result[0]:
                return False, {}, validation_result[1]

            # 更新当前轮次
            state['current_round'] = round_name
            state['draw_stage'] = round_name

            # 清空已抽签队长列表，允许新轮次重新抽签
            state['drawn_captains'] = []

            # 特殊处理决赛：直接创建比赛，不需要抽签
            if round_name == 'final':
                # 获取有资格参加决赛的队伍
                eligible_teams = self._get_eligible_teams_for_round(state, round_name)
                if len(eligible_teams) == 2:
                    # 直接创建决赛比赛
                    final_match = self.create_match('final', eligible_teams[0], eligible_teams[1])
                    state['matches'].append(final_match)
                    state['draw_enabled'] = False  # 决赛不需要抽签

                    # 更新队伍状态为已配对
                    for team in eligible_teams:
                        for original_team in state['teams']:
                            if original_team['id'] == team['id']:
                                original_team['status'] = 'final_paired'
                                break
                else:
                    return False, {}, f"决赛队伍数量错误，应为2队，实际为{len(eligible_teams)}队"
            else:
                # 其他轮次正常开启抽签
                state['draw_enabled'] = True

                # 如果是复活赛，确保只有上一轮的淘汰者可以参加
                if round_config['type'] == 'revival':
                    self._prepare_revival_round(state, round_name)

            if self.save_tournament_state(state):
                if round_name == 'final':
                    return True, state, f"决赛已开启，两队已自动配对完成"
                else:
                    return True, state, f"当前轮次已设置为: {round_config['display_name']}，抽签已开启"
            else:
                return False, {}, "保存状态失败"

        except Exception as e:
            return False, {}, f"设置当前轮次失败: {str(e)}"

    def _validate_round_switch_with_history(self, state: Dict, round_name: str, round_config: Dict) -> Tuple[bool, str]:
        """验证轮次切换的合法性（包含历史数据检查和只能向前切换的限制）"""
        try:
            # 获取当前轮次在配置中的索引
            target_round_index = -1
            current_round_index = -1

            for i, r in enumerate(self.config['rounds']):
                if r['name'] == round_name:
                    target_round_index = i
                if r['name'] == state.get('current_round'):
                    current_round_index = i

            if target_round_index == -1:
                return False, f"轮次 '{round_name}' 不在配置中"

            # 如果是第一轮，只需要有注册的队伍
            if target_round_index == 0:
                if not state.get('teams') or len(state['teams']) == 0:
                    return False, "没有注册的队伍，无法开始比赛"
                return True, ""

            # 特殊处理决赛：只检查能产生决赛队伍的轮次，跳过复活赛检查
            if round_name == 'final':
                return self._validate_final_round_switch(state, target_round_index)

            # 检查是否只能向前切换（不能回到之前的轮次）
            if current_round_index >= 0 and target_round_index <= current_round_index:
                current_round_display = self.config['rounds'][current_round_index].get('display_name', state.get('current_round'))
                target_round_display = round_config.get('display_name', round_name)
                return False, f"不能从{current_round_display}切换回{target_round_display}，只能向前切换到下一轮"

            # 检查是否是紧邻的下一轮（不能跳跃轮次）
            if current_round_index >= 0:
                next_valid_round = self._get_next_valid_round_index(state, current_round_index)
                if next_valid_round != target_round_index:
                    if next_valid_round == -1:
                        return False, "当前轮次的所有比赛尚未完成，无法切换到下一轮"
                    else:
                        next_round_display = self.config['rounds'][next_valid_round].get('display_name', self.config['rounds'][next_valid_round]['name'])
                        return False, f"请先切换到{next_round_display}，不能跳跃轮次"

            # 读取历史数据，检查前面所有轮次是否都已完成
            for i in range(target_round_index):
                prev_round = self.config['rounds'][i]
                prev_round_name = prev_round['name']

                # 检查前面轮次是否完成
                if not self._is_round_completed_with_history(state, prev_round_name):
                    prev_round_display = prev_round.get('display_name', prev_round_name)
                    return False, f"需要先完成{prev_round_display}的所有比赛"

            # 如果是复活赛，需要检查上一轮主要比赛是否完成并有淘汰队伍
            if round_config['type'] == 'revival':
                main_round_name = round_name.replace('_revival', '_main')

                # 检查对应的主要轮次是否存在并完成
                main_round_config = self.get_round_config(main_round_name)
                if not main_round_config:
                    return False, f"找不到对应的主要轮次: {main_round_name}"

                if not self._is_round_completed_with_history(state, main_round_name):
                    return False, f"需要先完成{main_round_config.get('display_name', main_round_name)}的所有比赛"

                # 检查是否有淘汰的队伍
                eliminated_teams = self._get_eliminated_teams(state, main_round_name)
                if len(eliminated_teams) == 0:
                    return False, "没有淘汰的队伍，无法开始复活赛"

                # 检查是否有复活名额
                if round_config.get('advance_count', 0) == 0:
                    return False, "该复活赛没有复活名额"

                return True, ""

            # 对于主要轮次，检查是否有足够的晋级队伍
            if round_config['type'] == 'main':
                # 获取应该参与当前轮次的队伍
                eligible_teams = self._get_eligible_teams_for_round(state, round_name)
                if len(eligible_teams) < round_config['groups_count'] * round_config['teams_per_group']:
                    return False, f"参与队伍数量不足，无法开始{round_config.get('display_name', round_name)}"

            return True, ""

        except Exception as e:
            return False, f"验证轮次切换失败: {str(e)}"

    def _validate_final_round_switch(self, state: Dict, target_round_index: int) -> Tuple[bool, str]:
        """验证决赛轮次切换的合法性（只检查能产生决赛队伍的轮次）"""
        try:
            # 获取有资格参加决赛的队伍
            eligible_teams = self._get_eligible_teams_for_round(state, 'final')

            # 检查是否有且仅有2支队伍
            if len(eligible_teams) != 2:
                if len(eligible_teams) == 0:
                    return False, "没有队伍有资格参加决赛，请先完成前面的比赛"
                elif len(eligible_teams) == 1:
                    return False, "只有1支队伍有资格参加决赛，需要2支队伍才能开始决赛"
                else:
                    return False, f"有{len(eligible_teams)}支队伍有资格参加决赛，但决赛只能有2支队伍"

            # 检查这些队伍是否来自已完成的轮次
            # 找到能产生决赛队伍的最后一个主要轮次
            last_main_round = None
            for i in range(target_round_index - 1, -1, -1):
                round_config = self.config['rounds'][i]
                if round_config['type'] == 'main':
                    last_main_round = round_config['name']
                    break

            if last_main_round:
                # 检查最后一个主要轮次是否完成
                if not self._is_round_completed_with_history(state, last_main_round):
                    last_main_round_config = self.get_round_config(last_main_round)
                    last_main_round_display = last_main_round_config.get('display_name', last_main_round) if last_main_round_config else last_main_round
                    return False, f"需要先完成{last_main_round_display}的所有比赛才能开始决赛"

            return True, ""

        except Exception as e:
            return False, f"验证决赛轮次切换失败: {str(e)}"

    def _get_next_valid_round_index(self, state: Dict, current_round_index: int) -> int:
        """获取下一个有效轮次的索引（跳过不需要的复活赛）"""
        try:
            # 检查当前轮次是否完成
            current_round = self.config['rounds'][current_round_index]
            if not self._is_round_completed_with_history(state, current_round['name']):
                return -1  # 当前轮次未完成

            # 查找下一个有效轮次
            for i in range(current_round_index + 1, len(self.config['rounds'])):
                next_round = self.config['rounds'][i]

                # 如果是复活赛，检查是否需要
                if next_round['type'] == 'revival':
                    if self._should_skip_revival_round(current_round['name'], next_round['name']):
                        continue  # 跳过这个复活赛

                return i

            return -1  # 没有下一轮

        except Exception as e:
            print(f"获取下一个有效轮次失败: {str(e)}")
            return -1

    def _is_round_completed_with_history(self, state: Dict, round_name: str) -> bool:
        """检查轮次是否完成（包含历史数据检查）"""
        try:
            # 获取轮次配置
            round_config = self.get_round_config(round_name)
            if not round_config:
                return False

            # 从历史数据中检查轮次完成状态
            round_results = state.get('round_results', {})
            if round_name in round_results:
                # 如果有明确的完成标记，使用它
                if 'completed' in round_results[round_name]:
                    return round_results[round_name]['completed']

            # 否则通过比赛记录检查
            round_matches = [m for m in state.get('matches', []) if m['round'] == round_name]
            expected_matches = round_config['groups_count']

            # 检查比赛数量和完成状态
            return (len(round_matches) == expected_matches and
                    all(m.get('completed', False) for m in round_matches))

        except Exception as e:
            print(f"检查轮次完成状态失败: {str(e)}")
            return False

    def get_available_next_rounds(self) -> Tuple[bool, List[Dict], str]:
        """获取可以切换的下一轮列表"""
        try:
            state = self.get_tournament_state()
            if not state:
                return False, [], "获取比赛状态失败"

            current_round = state.get('current_round')
            if not current_round:
                # 如果没有当前轮次，返回第一轮
                if self.config['rounds']:
                    first_round = self.config['rounds'][0]
                    return True, [{
                        'name': first_round['name'],
                        'display_name': first_round['display_name'],
                        'type': first_round['type'],
                        'can_switch': True,
                        'reason': '可以开始第一轮'
                    }], "获取成功"
                else:
                    return False, [], "没有配置的轮次"

            # 获取当前轮次索引
            current_round_index = -1
            for i, r in enumerate(self.config['rounds']):
                if r['name'] == current_round:
                    current_round_index = i
                    break

            if current_round_index == -1:
                return False, [], f"当前轮次 '{current_round}' 不在配置中"

            available_rounds = []

            # 检查下一个有效轮次
            next_round_index = self._get_next_valid_round_index(state, current_round_index)

            if next_round_index == -1:
                # 检查当前轮次是否完成
                if self._is_round_completed_with_history(state, current_round):
                    return True, [], "所有轮次已完成，比赛结束"
                else:
                    return True, [], "当前轮次尚未完成，无法切换到下一轮"
            else:
                next_round = self.config['rounds'][next_round_index]

                # 验证是否可以切换到下一轮
                validation_result = self._validate_round_switch_with_history(state, next_round['name'], next_round)

                available_rounds.append({
                    'name': next_round['name'],
                    'display_name': next_round['display_name'],
                    'type': next_round['type'],
                    'can_switch': validation_result[0],
                    'reason': validation_result[1] if not validation_result[0] else '可以切换到此轮次'
                })

            return True, available_rounds, "获取成功"

        except Exception as e:
            return False, [], f"获取可用轮次失败: {str(e)}"

    def _validate_round_switch(self, state: Dict, round_name: str, round_config: Dict) -> Tuple[bool, str]:
        """验证轮次切换的合法性（保留原方法以保持兼容性）"""
        return self._validate_round_switch_with_history(state, round_name, round_config)

    def _get_eliminated_teams(self, state: Dict, round_name: str) -> List[Dict]:
        """获取指定轮次的淘汰队伍"""
        try:
            eliminated_teams = []

            # 从比赛结果中获取淘汰队伍
            round_matches = [m for m in state.get('matches', []) if m['round'] == round_name and m.get('completed', False)]

            for match in round_matches:
                if match.get('loser'):
                    eliminated_teams.append(match['loser'])

            return eliminated_teams

        except Exception as e:
            print(f"获取淘汰队伍失败: {str(e)}")
            return []

    def _get_eligible_teams_for_round(self, state: Dict, round_name: str) -> List[Dict]:
        """获取有资格参与指定轮次的队伍"""
        print(f"\n=== 获取有资格队伍 ===")
        print(f"轮次: {round_name}")

        try:
            # 获取轮次配置
            round_config = self.get_round_config(round_name)
            if not round_config:
                print(f"❌ 找不到轮次配置: {round_name}")
                return []

            print(f"轮次类型: {round_config['type']}")
            print(f"轮次显示名: {round_config.get('display_name', round_name)}")

            # 如果是第一轮，返回所有注册的队伍
            if round_name == self.config['rounds'][0]['name']:
                teams = state.get('teams', [])
                print(f"第一轮，返回所有 {len(teams)} 支队伍")
                return teams

            # 特殊处理决赛：只返回最后一个主要轮次的获胜者
            if round_name == 'final':
                print("决赛轮次，获取决赛有资格队伍")
                return self._get_final_eligible_teams(state)

            # 如果是复活赛，返回对应主要轮次的淘汰队伍
            if round_config['type'] == 'revival':
                main_round_name = round_name.replace('_revival', '_main')
                print(f"复活赛，获取 {main_round_name} 的淘汰队伍")
                eliminated_teams = self._get_eliminated_teams(state, main_round_name)
                print(f"找到 {len(eliminated_teams)} 支淘汰队伍")
                for team in eliminated_teams:
                    print(f"  - {team['name']} (ID: {team['id']}, 状态: {team.get('status', 'unknown')})")
                return eliminated_teams

            # 如果是主要轮次，返回前面所有轮次的获胜者（包括比赛获胜者和轮空晋级者）
            print("主要轮次，收集前面轮次的获胜者")
            eligible_teams = []

            # 获取当前轮次在配置中的索引
            current_round_index = -1
            for i, r in enumerate(self.config['rounds']):
                if r['name'] == round_name:
                    current_round_index = i
                    break

            print(f"当前轮次索引: {current_round_index}")
            if current_round_index <= 0:
                print("当前轮次索引 <= 0，返回空列表")
                return []

            # 收集前面所有轮次的获胜者
            eligible_team_ids = set()  # 使用ID集合避免重复

            for i in range(current_round_index):
                prev_round = self.config['rounds'][i]
                prev_round_name = prev_round['name']
                print(f"\n--- 检查前置轮次: {prev_round_name} (类型: {prev_round['type']}) ---")

                # 方法1：从比赛结果中获取获胜者
                round_matches = [m for m in state.get('matches', []) if m['round'] == prev_round_name and m.get('completed', False)]
                print(f"该轮次已完成比赛数量: {len(round_matches)}")
                for match in round_matches:
                    if match.get('winner') and match['winner']['id'] not in eligible_team_ids:
                        print(f"  从比赛获胜者添加: {match['winner']['name']} (ID: {match['winner']['id']})")
                        eligible_teams.append(match['winner'])
                        eligible_team_ids.add(match['winner']['id'])

                # 方法2：从round_results中获取晋级队伍（包括轮空晋级）
                if 'round_results' in state and prev_round_name in state['round_results']:
                    advanced_teams = state['round_results'][prev_round_name].get('advanced', [])
                    print(f"round_results中的晋级队伍数量: {len(advanced_teams)}")
                    for team in advanced_teams:
                        if team['id'] not in eligible_team_ids:
                            print(f"  从round_results添加: {team['name']} (ID: {team['id']}, 状态: {team.get('status', 'unknown')})")
                            eligible_teams.append(team)
                            eligible_team_ids.add(team['id'])
                        else:
                            print(f"  跳过重复队伍: {team['name']} (ID: {team['id']})")

                # 方法3：特别处理复活赛轮空队伍（修复轮空队伍无法参与下一轮的bug）
                if prev_round['type'] == 'revival':
                    print(f"  特别处理复活赛轮次: {prev_round_name}")
                    # 从原始队伍列表中查找状态为'revived'的队伍
                    revived_teams_found = 0
                    for team in state.get('teams', []):
                        if (team.get('status') == 'revived' and
                            team['id'] not in eligible_team_ids):
                            print(f"    检查复活队伍: {team['name']} (ID: {team['id']}, 状态: {team.get('status')})")
                            # 验证这个队伍确实是从当前复活赛轮次晋级的
                            # 检查是否在该轮次的advanced列表中，或者检查旧的revival_teams列表
                            is_from_current_revival = False

                            # 检查新的round_results结构
                            if ('round_results' in state and
                                prev_round_name in state['round_results']):
                                advanced_list = state['round_results'][prev_round_name].get('advanced', [])
                                is_from_current_revival = any(t['id'] == team['id'] for t in advanced_list)
                                print(f"      在新结构中找到: {is_from_current_revival}")

                            # 如果新结构中没有，检查旧的revival_teams结构（兼容性）
                            if not is_from_current_revival and 'revival_teams' in state:
                                is_from_current_revival = any(t['id'] == team['id'] for t in state['revival_teams'])
                                print(f"      在旧结构中找到: {is_from_current_revival}")

                            if is_from_current_revival:
                                print(f"    ✅ 添加复活队伍: {team['name']} (ID: {team['id']})")
                                eligible_teams.append(team)
                                eligible_team_ids.add(team['id'])
                                revived_teams_found += 1
                            else:
                                print(f"    ❌ 复活队伍不属于当前轮次: {team['name']}")
                    print(f"  复活赛轮次共找到 {revived_teams_found} 支复活队伍")

            print(f"\n最终有资格队伍总数: {len(eligible_teams)}")
            for team in eligible_teams:
                print(f"  - {team['name']} (ID: {team['id']}, 状态: {team.get('status', 'unknown')})")

            return eligible_teams

        except Exception as e:
            print(f"获取符合条件队伍失败: {str(e)}")
            return []

    def _get_final_eligible_teams(self, state: Dict) -> List[Dict]:
        """获取有资格参加决赛的队伍（只从最后一个主要轮次获取）"""
        try:
            # 找到最后一个主要轮次
            last_main_round = None
            for round_config in reversed(self.config['rounds']):
                if round_config['type'] == 'main' and round_config['name'] != 'final':
                    last_main_round = round_config['name']
                    break

            if not last_main_round:
                return []

            eligible_teams = []
            eligible_team_ids = set()

            # 方法1：从比赛结果中获取获胜者
            round_matches = [m for m in state.get('matches', []) if m['round'] == last_main_round and m.get('completed', False)]
            for match in round_matches:
                if match.get('winner') and match['winner']['id'] not in eligible_team_ids:
                    eligible_teams.append(match['winner'])
                    eligible_team_ids.add(match['winner']['id'])

            # 方法2：从round_results中获取晋级队伍
            if 'round_results' in state and last_main_round in state['round_results']:
                advanced_teams = state['round_results'][last_main_round].get('advanced', [])
                for team in advanced_teams:
                    if team['id'] not in eligible_team_ids:
                        eligible_teams.append(team)
                        eligible_team_ids.add(team['id'])

            return eligible_teams

        except Exception as e:
            print(f"获取决赛符合条件队伍失败: {str(e)}")
            return []

    def _prepare_revival_round(self, state: Dict, round_name: str):
        """准备复活赛，确保只有上一轮淘汰者可以参加"""
        try:
            # 获取对应的主要轮次名称
            main_round_name = round_name.replace('_revival', '_main')

            # 获取上一轮的淘汰者
            eliminated_teams = self._get_eliminated_teams(state, main_round_name)

            # 确保复活赛结果结构存在
            if 'round_results' not in state:
                state['round_results'] = {}
            if round_name not in state['round_results']:
                state['round_results'][round_name] = {
                    'advanced': [],
                    'eliminated': [],
                    'groups': {},
                    'completed': False
                }

            # 记录可参加复活赛的队伍
            state['round_results'][round_name]['eligible_teams'] = eliminated_teams.copy()

            # 同时更新旧数据结构以保持兼容性
            # 如果是第一轮主要比赛，更新旧的数据结构
            if main_round_name == self.config['rounds'][0]['name']:
                state['round1_eliminated'] = eliminated_teams.copy()

        except Exception as e:
            print(f"准备复活赛失败: {str(e)}")

    def toggle_revival_round(self, round_name: str, enabled: bool) -> Tuple[bool, Dict, str]:
        """开启/关闭复活赛"""
        try:
            # 验证轮次是否存在且为复活赛类型
            round_config = self.get_round_config(round_name)
            if not round_config:
                return False, {}, f"轮次 '{round_name}' 不存在"

            if round_config['type'] != 'revival':
                return False, {}, f"轮次 '{round_name}' 不是复活赛类型"

            state = self.get_tournament_state()
            if not state:
                return False, {}, "获取比赛状态失败"

            # 初始化复活赛状态字段（如果不存在）
            if 'revival_rounds' not in state:
                state['revival_rounds'] = {}

            # 设置复活赛状态
            state['revival_rounds'][round_name] = enabled

            if self.save_tournament_state(state):
                status = "开启" if enabled else "关闭"
                return True, state, f"复活赛 '{round_config['display_name']}' 已{status}"
            else:
                return False, {}, "保存状态失败"

        except Exception as e:
            return False, {}, f"设置复活赛失败: {str(e)}"

    def toggle_elimination_mode(self, enabled: bool) -> Tuple[bool, Dict, str]:
        """开启/关闭淘汰赛模式"""
        try:
            state = self.get_tournament_state()
            if not state:
                return False, {}, "获取比赛状态失败"

            # 设置淘汰赛模式
            state['elimination_mode'] = enabled

            if self.save_tournament_state(state):
                status = "开启" if enabled else "关闭"
                return True, state, f"淘汰赛模式已{status}"
            else:
                return False, {}, "保存状态失败"

        except Exception as e:
            return False, {}, f"设置淘汰赛模式失败: {str(e)}"

    def get_tournament_state(self) -> Optional[Dict]:
        """获取比赛状态"""
        if self.redis_client:
            try:
                state_data = self.redis_client.get(self.tournament_key)
                if state_data:
                    return json.loads(state_data)
            except Exception as e:
                print(f"获取比赛状态失败: {e}")
        return None

    def save_tournament_state(self, state: Dict) -> bool:
        """保存比赛状态"""
        if self.redis_client:
            try:
                self.redis_client.set(self.tournament_key, json.dumps(state, ensure_ascii=False))
                return True
            except Exception as e:
                print(f"保存比赛状态失败: {e}")
        return False

    def create_team(self, name: str, captain: str) -> Dict:
        """创建队伍"""
        return {
            'id': str(uuid.uuid4()),
            'name': name,
            'captain': captain,
            'group': None,
            'status': 'registered',
            'round_eliminated': None,
            'round_advanced': None,
            'revival_source': None  # 复活赛来源标识：None=非复活队伍, 'revival'=复活赛晋级, 'bye'=轮空复活
        }

    def create_match(self, round_name: str, team1: Dict, team2: Dict, group: str = None) -> Dict:
        """创建比赛"""
        match = {
            'id': str(uuid.uuid4()),
            'round': round_name,
            'team1': team1,
            'team2': team2,
            'winner': None,
            'loser': None,
            'completed': False,
            'match_time': datetime.now().isoformat()
        }
        if group:
            match['group'] = group
        return match

    def register_teams(self, teams_data: List[Dict]) -> Tuple[bool, Dict, str]:
        """注册队伍（管理员操作）"""
        try:
            if len(teams_data) != self.config['total_teams']:
                return False, {}, f"队伍数量必须为{self.config['total_teams']}队"

            # 创建队伍
            teams = []
            for team_data in teams_data:
                team = self.create_team(team_data['name'], team_data['captain'])
                teams.append(team)

            # 初始化比赛状态 - 动态设置第一轮
            first_round = self.config['rounds'][0]['name'] if self.config['rounds'] else 'round1_main'
            tournament_state = {
                'current_round': first_round,  # 动态设置第一轮
                'draw_enabled': True,   # 自动开启第一轮抽签
                'draw_stage': first_round,  # 当前抽签阶段为第一轮
                'teams': teams,
                'matches': [],
                'round_results': {},  # 存储每轮的结果（新数据结构）
                'champion': None,
                'runner_up': None,
                'drawn_captains': [],    # 已抽签的队长列表
                # 兼容旧数据结构的字段
                'round1_advanced': [],
                'round1_eliminated': [],
                'revival_teams': [],
                'round2_teams': [],
                'round3_teams': [],
                'final_teams': []
            }

            # 为每轮初始化结果存储
            for round_config in self.config['rounds']:
                round_name = round_config['name']
                tournament_state['round_results'][round_name] = {
                    'advanced': [],
                    'eliminated': [],
                    'groups': {},
                    'completed': False
                }

            if self.save_tournament_state(tournament_state):
                return True, tournament_state, "队伍注册成功"
            else:
                return False, {}, "保存队伍信息失败"

        except Exception as e:
            return False, {}, f"注册队伍失败: {str(e)}"

    def enable_draw_for_round(self, round_name: str) -> Tuple[bool, Dict, str]:
        """为指定轮次开启抽签（决赛会自动配对）"""
        state = self.get_tournament_state()
        if not state:
            return False, {}, "获取比赛状态失败"

        try:
            # 验证轮次是否存在
            round_config = self.get_round_config(round_name)
            if not round_config:
                return False, {}, f"轮次 '{round_name}' 不存在"

            # 如果是决赛，直接调用set_current_round来处理自动配对
            if round_name == 'final':
                return self.set_current_round(round_name)

            # 设置当前轮次和抽签状态
            state['current_round'] = round_name
            state['draw_enabled'] = True
            state['draw_stage'] = round_name

            # 重置已抽签队长列表（新轮次开始）
            state['drawn_captains'] = []

            if self.save_tournament_state(state):
                return True, state, f"已开启{round_config['display_name']}抽签"
            else:
                return False, {}, "保存状态失败"

        except Exception as e:
            return False, {}, f"开启抽签失败: {str(e)}"

    def disable_draw(self) -> Tuple[bool, Dict, str]:
        """关闭抽签"""
        state = self.get_tournament_state()
        if not state:
            return False, {}, "获取比赛状态失败"

        try:
            state['draw_enabled'] = False
            # 保留 draw_stage 信息，只是禁用抽签

            if self.save_tournament_state(state):
                return True, state, "已关闭抽签"
            else:
                return False, {}, "保存状态失败"

        except Exception as e:
            return False, {}, f"关闭抽签失败: {str(e)}"

    def captain_draw(self, captain_name: str) -> Tuple[bool, Dict, str]:
        """队长抽签（队长操作）"""
        print(f"\n=== 队长抽签开始 ===")
        print(f"队长姓名: {captain_name}")

        state = self.get_tournament_state()
        if not state:
            print("❌ 获取比赛状态失败")
            return False, {}, "获取比赛状态失败"

        try:
            # 检查是否允许抽签
            print(f"抽签开启状态: {state.get('draw_enabled', False)}")
            if not state.get('draw_enabled', False):
                print("❌ 当前不允许抽签")
                return False, {}, "当前不允许抽签，请等待管理员开启"

            # 检查队长是否存在
            captain_team = None
            print(f"查找队长 '{captain_name}' 在队伍列表中...")
            for team in state['teams']:
                print(f"  检查队伍: {team['name']}, 队长: {team['captain']}, 状态: {team.get('status', 'unknown')}")
                if team['captain'] == captain_name:
                    captain_team = team
                    break

            if not captain_team:
                print(f"❌ 队长 '{captain_name}' 不存在")
                return False, {}, "队长不存在，请检查姓名"

            print(f"✅ 找到队长队伍: {captain_team['name']}, ID: {captain_team['id']}, 状态: {captain_team.get('status', 'unknown')}")

            # 检查是否已经抽过签
            drawn_captains = state.get('drawn_captains', [])
            print(f"已抽签队长列表: {drawn_captains}")
            if captain_name in drawn_captains:
                print(f"❌ 队长 '{captain_name}' 已经抽过签")
                return False, {}, "该队长已经抽过签了"

            # 获取当前抽签阶段
            draw_stage = state.get('draw_stage')
            print(f"当前抽签阶段: {draw_stage}")
            if not draw_stage:
                print("❌ 当前没有进行中的抽签阶段")
                return False, {}, "当前没有进行中的抽签阶段"

            # 验证队伍是否有资格参加当前轮次
            print(f"\n--- 检查队伍资格 ---")
            eligible_teams = self._get_eligible_teams_for_round(state, draw_stage)
            print(f"有资格参加 '{draw_stage}' 的队伍数量: {len(eligible_teams)}")
            for i, team in enumerate(eligible_teams):
                print(f"  {i+1}. {team['name']} (ID: {team['id']}, 状态: {team.get('status', 'unknown')})")

            team_eligible = False
            for eligible_team in eligible_teams:
                if eligible_team['id'] == captain_team['id']:
                    team_eligible = True
                    break

            print(f"队伍 '{captain_team['name']}' 是否有资格: {team_eligible}")

            if not team_eligible:
                round_config = self.get_round_config(draw_stage)
                round_display_name = round_config.get('display_name', draw_stage) if round_config else draw_stage
                print(f"❌ 队伍没有资格参加 {round_display_name}")

                if round_config and round_config['type'] == 'revival':
                    return False, {}, f"队伍没有资格参加{round_display_name}（只有上一轮淘汰的队伍可以参加）"
                else:
                    return False, {}, f"队伍没有资格参加{round_display_name}（只有前面轮次获胜的队伍可以参加）"

            # 根据当前抽签阶段进行相应的抽签逻辑
            print(f"\n--- 抽签逻辑分发 ---")
            round_config = self.get_round_config(draw_stage)
            if not round_config:
                print(f"❌ 找不到轮次配置: {draw_stage}")
                return False, {}, f"找不到轮次配置: {draw_stage}"

            print(f"轮次类型: {round_config['type']}")

            # 特殊处理决赛：决赛不需要抽签
            if draw_stage == 'final':
                print("❌ 决赛已自动配对，无需抽签")
                return False, {}, "决赛已自动配对，无需抽签"

            # 使用通用的抽签处理方法
            if round_config['type'] == 'revival':
                print("✅ 进入复活赛抽签处理")
                return self._handle_revival_draw(state, captain_team, captain_name)
            else:
                print("✅ 进入主要轮次抽签处理")
                return self._handle_main_round_draw(state, captain_team, captain_name, draw_stage)

        except Exception as e:
            print(f"❌ 抽签异常: {str(e)}")
            print(f"=== 队长抽签结束 ===\n")
            return False, {}, f"抽签失败: {str(e)}"

    def _handle_main_round_draw(self, state: Dict, team: Dict, captain_name: str, round_name: str) -> Tuple[bool, Dict, str]:
        """处理主要轮次抽签（通用方法）"""
        try:
            # 获取轮次配置
            round_config = self.get_round_config(round_name)
            if not round_config:
                return False, {}, f"找不到轮次配置: {round_name}"

            # 检查是否已经抽过签
            if captain_name in state['drawn_captains']:
                return False, {}, "该队长已经抽过签"

            # 初始化轮次分组信息（如果还没有）
            round_key = f'{round_name}_groups'
            if round_key not in state:
                state[round_key] = {}
                for i in range(round_config['groups_count']):
                    group_name = chr(65 + i)  # A, B, C, D, E...
                    state[round_key][group_name] = []

            # 找到还有空位的组
            available_groups = []
            for group_name, teams_in_group in state[round_key].items():
                if len(teams_in_group) < round_config['teams_per_group']:
                    available_groups.append(group_name)

            if not available_groups:
                return False, {}, "所有组别已满"

            # 检查当前队伍是否来自复活赛
            is_revival_team = team.get('revival_source') is not None

            # 如果是复活赛队伍，只能分到前三组（A、B、C）
            if is_revival_team:
                print(f"队伍 '{team['name']}' 来自复活赛 (来源: {team.get('revival_source')})")

                # 复活赛队伍只能选择前三组（A、B、C）
                revival_allowed_groups = ['A', 'B', 'C']

                # 检查前三组的可用性（不依赖available_groups，直接检查前三组）
                revival_available_groups = []
                for group_name in revival_allowed_groups:
                    if group_name in state[round_key]:
                        teams_in_group = state[round_key][group_name]
                        if len(teams_in_group) < round_config['teams_per_group']:
                            revival_available_groups.append(group_name)
                    else:
                        # 组还不存在，可以创建
                        revival_available_groups.append(group_name)

                print(f"复活赛队伍可选组别: {revival_available_groups}")

                if not revival_available_groups:
                    print(f"❌ 前三组已满，复活赛队伍无法抽签")
                    return False, {}, "前三组已满，复活赛队伍无法抽签"

                # 在前三组中找到可以进入的组（强制配对逻辑）
                available_revival_groups = []
                for group_name in revival_available_groups:
                    teams_in_group = state[round_key].get(group_name, [])
                    has_revival_team = any(t.get('revival_source') is not None for t in teams_in_group)

                    # 复活赛队伍可以进入的条件：
                    # 该组不能已经有复活赛队伍（每组最多一个复活赛队伍）
                    # 可以进入空组或只有非复活赛队伍的组
                    if not has_revival_team:  # 该组没有复活赛队伍
                        available_revival_groups.append(group_name)

                print(f"复活赛队伍可进入的前三组: {available_revival_groups}")

                if available_revival_groups:
                    # 选择可进入的组
                    selected_group = random.choice(available_revival_groups)
                    print(f"为复活赛队伍选择组: {selected_group}")
                else:
                    # 如果前三组都已有复活赛队伍，则无法抽签
                    print(f"❌ 前三组都已有复活赛队伍，无法分配新的复活赛队伍")
                    return False, {}, "前三组都已有复活赛队伍，无法分配新的复活赛队伍"
            else:
                # 非复活赛队伍，需要避免抽到已有非复活赛队伍的前三组（强制性限制）
                print(f"非复活赛队伍 '{team['name']}' 开始抽签")

                # 检查前三组中哪些已经有非复活赛队伍
                front_three_groups = ['A', 'B', 'C']
                groups_with_non_revival = []

                for group_name in front_three_groups:
                    if group_name in state[round_key]:
                        teams_in_group = state[round_key][group_name]
                        has_non_revival_team = any(t.get('revival_source') is None for t in teams_in_group)

                        if has_non_revival_team:
                            groups_with_non_revival.append(group_name)

                print(f"前三组中已有非复活赛队伍的组: {groups_with_non_revival}")

                # 强制性限制：如果前三组中有一个组已经有非复活赛队伍，
                # 其他非复活赛队伍不能再进入该组
                filtered_available_groups = []
                for group_name in available_groups:
                    if group_name in groups_with_non_revival:
                        print(f"排除组 {group_name}（已有非复活赛队伍，强制性限制）")
                        continue
                    else:
                        # 可以进入其他组
                        filtered_available_groups.append(group_name)

                print(f"非复活赛队伍可选组别: {filtered_available_groups}")

                if not filtered_available_groups:
                    print(f"❌ 没有可用组别，非复活赛队伍无法抽签")
                    return False, {}, "没有可用组别，非复活赛队伍无法抽签"

                # 从过滤后的组中随机选择
                selected_group = random.choice(filtered_available_groups)
                print(f"非复活赛队伍选择组: {selected_group}")

                # 如果非复活赛队伍抽到前三组，记录重要信息
                if selected_group in front_three_groups:
                    print(f"🔒 非复活赛队伍进入前三组 {selected_group}，该组将专属于复活赛队伍配对")

            # 将队伍添加到选中的组
            state[round_key][selected_group].append(team)

            # 记录已抽签队长
            state['drawn_captains'].append(captain_name)

            # 更新队伍状态
            team[f'{round_name}_group'] = selected_group
            team['status'] = f'{round_name}_drawn'

            # 检查该组是否已满，如果满了就创建比赛
            if len(state[round_key][selected_group]) == round_config['teams_per_group']:
                teams_in_group = state[round_key][selected_group]
                if len(teams_in_group) == 2:
                    team1, team2 = teams_in_group
                    match = self.create_match(round_name, team1, team2, selected_group)
                    state['matches'].append(match)

            if self.save_tournament_state(state):
                return True, {
                    'group': selected_group,
                    'team': team,
                    'round': round_name
                }, f"抽签成功，分配到{selected_group}"
            else:
                return False, {}, "保存抽签结果失败"

        except Exception as e:
            return False, {}, f"{round_name}抽签失败: {str(e)}"



    def _handle_revival_draw(self, state: Dict, team: Dict, captain_name: str) -> Tuple[bool, Dict, str]:
        """处理复活赛抽签"""
        print(f"\n=== 复活赛抽签处理 ===")
        print(f"队伍: {team['name']} (ID: {team['id']}, 状态: {team.get('status', 'unknown')})")
        print(f"队长: {captain_name}")

        try:
            # 获取当前抽签阶段的复活赛配置
            current_draw_stage = state.get('draw_stage')
            print(f"当前抽签阶段: {current_draw_stage}")

            round_config = self.get_round_config(current_draw_stage)
            if not round_config or round_config['type'] != 'revival':
                print(f"❌ 当前不是复活赛阶段，轮次配置: {round_config}")
                return False, {}, "当前不是复活赛阶段"

            print(f"复活赛配置: {round_config}")

            # 检查队伍是否有资格参加复活赛
            print(f"\n--- 检查复活赛资格 ---")
            # 首先尝试从新数据结构获取
            revival_round_results = state.get('round_results', {}).get(current_draw_stage, {})
            eligible_teams = revival_round_results.get('eligible_teams', [])
            print(f"从新数据结构获取的有资格队伍数量: {len(eligible_teams)}")

            # 如果新数据结构为空，则从旧数据结构获取（兼容性处理）
            if not eligible_teams:
                print("新数据结构为空，尝试从旧数据结构获取...")
                # 获取对应的主要轮次名称
                main_round_name = current_draw_stage.replace('_revival', '_main')
                print(f"对应主要轮次: {main_round_name}")

                if main_round_name in state.get('round_results', {}):
                    eligible_teams = state['round_results'][main_round_name].get('eliminated', [])
                    print(f"从 round_results[{main_round_name}].eliminated 获取 {len(eligible_teams)} 支队伍")
                else:
                    # 如果新数据结构也没有，使用旧的兼容字段
                    eligible_teams = state.get('round1_eliminated', [])
                    print(f"从 round1_eliminated 获取 {len(eligible_teams)} 支队伍")

            print(f"有资格参加复活赛的队伍:")
            for i, eligible_team in enumerate(eligible_teams):
                print(f"  {i+1}. {eligible_team['name']} (ID: {eligible_team['id']}, 状态: {eligible_team.get('status', 'unknown')})")

            # 检查队伍是否在有资格的队伍列表中
            team_eligible = False
            for eligible_team in eligible_teams:
                if eligible_team['id'] == team['id']:
                    team_eligible = True
                    break

            print(f"队伍 '{team['name']}' 是否有资格参加复活赛: {team_eligible}")
            if not team_eligible:
                print("❌ 队伍没有资格参加当前复活赛")
                return False, {}, "队伍没有资格参加当前复活赛"

            # 检查是否已经抽过签
            drawn_captains = state.get('drawn_captains', [])
            print(f"已抽签队长列表: {drawn_captains}")
            if captain_name in drawn_captains:
                print(f"❌ 队长 '{captain_name}' 已经抽过签")
                return False, {}, "该队长已经抽过签"

            # 初始化复活赛分组信息（如果还没有）
            round_key = f'{current_draw_stage}_groups'
            print(f"复活赛分组键: {round_key}")
            if round_key not in state:
                print(f"初始化复活赛分组，组数: {round_config['groups_count']}")
                state[round_key] = {}
                for i in range(round_config['groups_count']):
                    group_name = chr(65 + i)  # A, B, C, D, E...
                    state[round_key][group_name] = []
                    print(f"  创建组: {group_name}")

            # 找到还有空位的组
            available_groups = []
            print(f"\n--- 检查可用组别 ---")
            for group_name, teams_in_group in state[round_key].items():
                print(f"组 {group_name}: {len(teams_in_group)}/{round_config['teams_per_group']} 队伍")
                for team_in_group in teams_in_group:
                    print(f"  - {team_in_group['name']}")
                if len(teams_in_group) < round_config['teams_per_group']:
                    available_groups.append(group_name)

            print(f"可用组别: {available_groups}")

            if not available_groups:
                print("没有可用组别，检查轮空情况...")
                # 检查是否还有复活名额（轮空情况）
                revival_teams = revival_round_results.get('advanced', [])
                print(f"当前已复活队伍数: {len(revival_teams)}, 最大复活数: {round_config['advance_count']}")
                if len(revival_teams) >= round_config['advance_count']:
                    print("❌ 复活名额已满")
                    return False, {}, "复活名额已满"

                # 没有可用组别，直接复活（轮空）
                print(f"✅ 队伍 '{team['name']}' 轮空直接复活")

                # 使用统一的轮空处理方法
                self._handle_bye_team_advancement(state, team, current_draw_stage, "轮空")
                state['drawn_captains'].append(captain_name)

                if self.save_tournament_state(state):
                    print("✅ 轮空复活保存成功")
                    return True, {
                        'bye': True,
                        'team': team
                    }, "恭喜！轮空直接复活"
                else:
                    print("❌ 保存抽签结果失败")
                    return False, {}, "保存抽签结果失败"

            # 随机选择一个组
            selected_group = random.choice(available_groups)
            print(f"✅ 随机选择组别: {selected_group}")

            # 将队伍添加到选中的组
            state[round_key][selected_group].append(team)
            print(f"将队伍 '{team['name']}' 添加到组 {selected_group}")

            # 记录已抽签队长
            state['drawn_captains'].append(captain_name)
            print(f"记录已抽签队长: {captain_name}")

            # 更新队伍状态
            team[f'{current_draw_stage}_group'] = selected_group
            team['status'] = f'{current_draw_stage}_drawn'
            print(f"更新队伍状态: {team['name']} -> {team['status']}")

            # 检查该组是否已满，如果满了就创建比赛或处理轮空
            teams_in_group = state[round_key][selected_group]
            print(f"组 {selected_group} 当前队伍数: {len(teams_in_group)}")

            # 对于复活赛，需要特殊处理：
            # - 如果组有2队，创建比赛
            # - 如果组有1队且所有队伍都已抽签，该队轮空晋级
            if len(teams_in_group) == 2:
                # 创建对战比赛
                team1, team2 = teams_in_group
                print(f"组 {selected_group} 已满，创建比赛: {team1['name']} vs {team2['name']}")
                match = self.create_match(current_draw_stage, team1, team2, selected_group)
                state['matches'].append(match)
            elif len(teams_in_group) == 1:
                print(f"组 {selected_group} 只有1支队伍，检查是否需要轮空...")
                # 检查是否所有队伍都已抽签完毕
                eligible_teams = self._get_eligible_teams_for_round(state, current_draw_stage)
                drawn_captains = state.get('drawn_captains', [])
                print(f"已抽签队长数: {len(drawn_captains)}, 有资格队伍数: {len(eligible_teams)}")

                if len(drawn_captains) >= len(eligible_teams):
                    # 所有队伍都已抽签，处理轮空
                    bye_team = teams_in_group[0]
                    print(f"✅ 所有队伍已抽签完毕，队伍 '{bye_team['name']}' 在组 {selected_group} 轮空晋级")

                    # 调用统一的轮空处理方法
                    self._handle_bye_team_advancement(state, bye_team, current_draw_stage, selected_group)
                else:
                    print(f"还有队伍未抽签，等待后续抽签...")

            # 在每次抽签后检查是否需要处理轮空（修复bug的关键）
            print(f"\n--- 检查轮空处理 ---")
            self._check_revival_bye_after_draw(state, current_draw_stage)

            if self.save_tournament_state(state):
                print(f"✅ 复活赛抽签保存成功")
                print(f"=== 复活赛抽签结束 ===\n")
                return True, {
                    'group': selected_group,
                    'team': team,
                    'round': current_draw_stage
                }, f"抽签成功，分配到{selected_group}组"
            else:
                print(f"❌ 保存抽签结果失败")
                print(f"=== 复活赛抽签结束 ===\n")
                return False, {}, "保存抽签结果失败"

        except Exception as e:
            print(f"❌ 复活赛抽签异常: {str(e)}")
            print(f"=== 复活赛抽签结束 ===\n")
            return False, {}, f"复活赛抽签失败: {str(e)}"

    def _handle_bye_team_advancement(self, state: Dict, bye_team: Dict, round_name: str, group_name: str):
        """统一处理轮空队伍晋级的方法"""
        print(f"\n=== 处理轮空队伍晋级 ===")
        print(f"队伍: {bye_team['name']} (ID: {bye_team['id']})")
        print(f"轮次: {round_name}, 组别: {group_name}")

        try:
            # 更新队伍状态为复活
            bye_team['status'] = 'revived'
            # 添加复活赛标识
            bye_team['revival_source'] = 'bye'  # 标记为轮空复活
            print(f"更新队伍状态: {bye_team['name']} -> 'revived', 复活来源: 轮空")

            # 确保复活赛结果结构存在
            if 'round_results' not in state:
                state['round_results'] = {}
            if round_name not in state['round_results']:
                state['round_results'][round_name] = {
                    'advanced': [],
                    'eliminated': [],
                    'groups': {},
                    'completed': False
                }

            # 添加到晋级队伍列表（避免重复）
            advanced_list = state['round_results'][round_name]['advanced']
            if not any(t['id'] == bye_team['id'] for t in advanced_list):
                print(f"添加轮空队伍到 round_results[{round_name}].advanced")
                advanced_list.append(bye_team.copy())  # 使用副本避免引用问题
            else:
                print(f"队伍已在晋级列表中，跳过添加")

            # 同时更新旧数据结构以保持兼容性
            if 'revival_teams' not in state:
                state['revival_teams'] = []
            if not any(t['id'] == bye_team['id'] for t in state['revival_teams']):
                print(f"添加轮空队伍到 revival_teams")
                state['revival_teams'].append(bye_team.copy())
            else:
                print(f"队伍已在revival_teams中，跳过添加")

            # 重要：同步更新原始队伍列表中的状态和复活标识
            for original_team in state['teams']:
                if original_team['id'] == bye_team['id']:
                    print(f"更新原始队伍状态: {original_team['name']} -> 'revived', 复活来源: 轮空")
                    original_team['status'] = 'revived'
                    original_team['revival_source'] = 'bye'  # 添加复活赛标识
                    # 设置晋级轮次信息
                    original_team['round_advanced'] = round_name
                    break

            print(f"✅ 队伍 {bye_team['name']} 在 {group_name} 组轮空晋级处理完成")

        except Exception as e:
            print(f"❌ 处理轮空队伍晋级失败: {str(e)}")

    def _check_revival_bye_after_draw(self, state: Dict, round_name: str):
        """在复活赛抽签后检查并处理轮空情况"""
        print(f"检查复活赛轮空情况: {round_name}")

        try:
            round_config = self.get_round_config(round_name)
            if not round_config or round_config['type'] != 'revival':
                print(f"不是复活赛轮次，跳过轮空检查")
                return

            # 获取当前轮次的分组
            round_key = f'{round_name}_groups'
            if round_key not in state:
                print(f"没有找到分组数据: {round_key}")
                return

            groups = state[round_key]
            print(f"当前分组情况:")
            for group_name, teams_in_group in groups.items():
                print(f"  组 {group_name}: {len(teams_in_group)} 支队伍")
                for team in teams_in_group:
                    print(f"    - {team['name']} (状态: {team.get('status', 'unknown')})")

            # 检查每个组，找出只有一支队伍的组
            for group_name, teams_in_group in groups.items():
                if len(teams_in_group) == 1:
                    bye_team = teams_in_group[0]
                    # 检查这支队伍是否已经处理过轮空
                    if bye_team.get('status') != 'revived':
                        print(f"发现需要轮空的队伍: {bye_team['name']} 在组 {group_name}")
                        self._handle_bye_team_advancement(state, bye_team, round_name, group_name)
                    else:
                        print(f"队伍 {bye_team['name']} 已经处理过轮空")

        except Exception as e:
            print(f"❌ 检查复活赛轮空失败: {str(e)}")
    def _check_and_handle_bye_advancement(self, state: Dict, round_name: str):
        """检查并处理轮空晋级（复活赛抽签结束后）"""
        try:
            # 只处理复活赛
            round_config = self.get_round_config(round_name)
            if not round_config or round_config['type'] != 'revival':
                return

            # 检查是否所有有资格的队伍都已抽签
            eligible_teams = self._get_eligible_teams_for_round(state, round_name)
            drawn_captains = state.get('drawn_captains', [])

            # 如果还有队伍没抽签，不处理轮空
            if len(drawn_captains) < len(eligible_teams):
                return

            # 获取当前轮次的分组
            round_key = f'{round_name}_groups'
            if round_key not in state:
                return

            groups = state[round_key]

            # 检查每个组，找出只有一支队伍的组
            for group_name, teams_in_group in groups.items():
                if len(teams_in_group) == 1:
                    # 这支队伍轮空晋级
                    bye_team = teams_in_group[0]
                    bye_team['status'] = 'revived'
                    bye_team['revival_source'] = 'bye'  # 添加复活赛标识

                    # 确保复活赛结果结构存在
                    if 'round_results' not in state:
                        state['round_results'] = {}
                    if round_name not in state['round_results']:
                        state['round_results'][round_name] = {
                            'advanced': [],
                            'eliminated': [],
                            'groups': {},
                            'completed': False
                        }

                    # 添加到晋级队伍列表（避免重复添加）
                    if bye_team not in state['round_results'][round_name]['advanced']:
                        state['round_results'][round_name]['advanced'].append(bye_team)

                    # 同时更新旧数据结构以保持兼容性
                    if 'revival_teams' not in state:
                        state['revival_teams'] = []
                    if bye_team not in state['revival_teams']:
                        state['revival_teams'].append(bye_team)

                    # 重要：同步更新原始队伍列表中的状态和复活标识
                    for original_team in state['teams']:
                        if original_team['id'] == bye_team['id']:
                            original_team['status'] = 'revived'
                            original_team['revival_source'] = 'bye'  # 添加复活赛标识
                            break

                    print(f"队伍 {bye_team['name']} 在 {group_name} 组轮空晋级")

            # 保存状态
            self.save_tournament_state(state)

        except Exception as e:
            print(f"处理轮空晋级失败: {str(e)}")

    def _sync_match_results_to_round_results(self, state: Dict, round_name: str):
        """同步比赛结果到round_results结构中，确保获胜者被正确记录"""
        try:
            # 确保round_results结构存在
            if 'round_results' not in state:
                state['round_results'] = {}
            if round_name not in state['round_results']:
                state['round_results'][round_name] = {
                    'advanced': [],
                    'eliminated': [],
                    'groups': {},
                    'completed': False
                }

            # 获取该轮次的所有已完成比赛
            round_matches = [m for m in state.get('matches', []) if m['round'] == round_name and m.get('completed', False)]

            for match in round_matches:
                # 添加获胜者到晋级列表
                if match.get('winner'):
                    winner = match['winner']
                    if winner not in state['round_results'][round_name]['advanced']:
                        state['round_results'][round_name]['advanced'].append(winner)

                # 添加失败者到淘汰列表
                if match.get('loser'):
                    loser = match['loser']
                    if loser not in state['round_results'][round_name]['eliminated']:
                        state['round_results'][round_name]['eliminated'].append(loser)

        except Exception as e:
            print(f"同步比赛结果失败: {str(e)}")






    def draw_round1_main(self) -> Tuple[bool, List[Dict], str]:
        """第一轮晋级赛抽签"""
        state = self.get_tournament_state()
        if not state:
            return False, [], "获取比赛状态失败"

        if state['current_round'] != 'round1_main':
            return False, [], "当前不是第一轮抽签阶段"

        try:
            teams = state['teams'].copy()
            random.shuffle(teams)

            # 10队分成5对进行比赛
            matches = []
            for i in range(0, len(teams), 2):
                if i + 1 < len(teams):
                    match = self.create_match('round1_main', teams[i], teams[i + 1])
                    matches.append(match)

            state['matches'].extend(matches)
            state['current_round'] = 'round1_main'

            if self.save_tournament_state(state):
                return True, matches, "第一轮抽签完成"
            else:
                return False, [], "保存抽签结果失败"

        except Exception as e:
            return False, [], f"第一轮抽签失败: {str(e)}"

    def submit_match_result(self, match_id: str, winner_team_id: str) -> Tuple[bool, Dict, str]:
        """提交比赛结果"""
        state = self.get_tournament_state()
        if not state:
            return False, {}, "获取比赛状态失败"

        try:
            # 找到对应的比赛
            match = None
            for m in state['matches']:
                if m['id'] == match_id:
                    match = m
                    break

            if not match:
                return False, {}, "比赛不存在"

            if match['completed']:
                return False, {}, "比赛已经完成"

            # 确定胜负方
            if match['team1']['id'] == winner_team_id:
                winner = match['team1']
                loser = match['team2']
            elif match['team2']['id'] == winner_team_id:
                winner = match['team2']
                loser = match['team1']
            else:
                return False, {}, "获胜队伍ID无效"

            # 更新比赛结果
            match['winner'] = winner
            match['loser'] = loser
            match['completed'] = True

            # 更新队伍状态
            round_config = self.get_round_config(match['round'])
            for team in state['teams']:
                if team['id'] == winner['id']:
                    # 如果是复活赛获胜者，设置特殊状态和标识
                    if round_config and round_config['type'] == 'revival':
                        team['status'] = 'revived'
                        team['revival_source'] = 'revival'  # 标记为复活赛获胜
                    else:
                        team['status'] = 'advanced'
                    team['round_advanced'] = match['round']
                elif team['id'] == loser['id']:
                    team['status'] = 'eliminated'
                    team['round_eliminated'] = match['round']

            # 根据轮次更新相应的晋级/淘汰列表
            round_name = match['round']

            # 更新新的数据结构
            if round_name in state['round_results']:
                # 添加到晋级列表
                if winner not in state['round_results'][round_name]['advanced']:
                    state['round_results'][round_name]['advanced'].append(winner)

                # 添加到淘汰列表（除了复活赛和决赛）
                if round_name not in ['round1_revival', 'final']:
                    if loser not in state['round_results'][round_name]['eliminated']:
                        state['round_results'][round_name]['eliminated'].append(loser)

            # 同时更新旧的数据结构以保持兼容性
            # 如果是第一轮主要比赛，更新旧的数据结构
            if round_name == self.config['rounds'][0]['name']:
                # 确保旧数据结构字段存在
                if 'round1_advanced' not in state:
                    state['round1_advanced'] = []
                if 'round1_eliminated' not in state:
                    state['round1_eliminated'] = []

                if winner not in state['round1_advanced']:
                    state['round1_advanced'].append(winner)
                if loser not in state['round1_eliminated']:
                    state['round1_eliminated'].append(loser)
            elif round_name.endswith('_revival'):
                # 确保复活队伍列表存在
                if 'revival_teams' not in state:
                    state['revival_teams'] = []
                if winner not in state['revival_teams']:
                    state['revival_teams'].append(winner)

            # 同步比赛结果到round_results结构（确保所有获胜者都被正确记录）
            self._sync_match_results_to_round_results(state, round_name)

            # 检查当前轮次是否完成，如果完成则自动标记轮次完成状态并准备下一轮
            round_completed = self._check_and_mark_round_completion(state, round_name)
            next_round_prepared = False

            if round_completed:
                # 尝试自动准备下一轮
                next_round_prepared = self._auto_prepare_next_round(state, round_name)

            if self.save_tournament_state(state):
                message = "比赛结果提交成功"
                if round_completed:
                    round_config = self.get_round_config(round_name)
                    round_display_name = round_config['display_name'] if round_config else round_name
                    message += f"，{round_display_name}已全部完成"

                    if next_round_prepared:
                        message += "，下一轮已自动准备就绪"

                return True, match, message
            else:
                return False, {}, "保存比赛结果失败"

        except Exception as e:
            return False, {}, f"提交比赛结果失败: {str(e)}"

    def _check_and_mark_round_completion(self, state: Dict, round_name: str) -> bool:
        """检查并标记轮次完成状态"""
        try:
            # 获取轮次配置
            round_config = self.get_round_config(round_name)
            if not round_config:
                return False

            # 检查当前轮次的所有比赛是否完成
            round_matches = [m for m in state['matches'] if m['round'] == round_name]
            expected_matches = round_config['groups_count']

            # 如果比赛数量和完成状态都符合要求
            if len(round_matches) == expected_matches and all(m['completed'] for m in round_matches):
                # 标记轮次完成
                if 'round_results' not in state:
                    state['round_results'] = {}
                if round_name not in state['round_results']:
                    state['round_results'][round_name] = {
                        'advanced': [],
                        'eliminated': [],
                        'groups': {},
                        'completed': False
                    }

                state['round_results'][round_name]['completed'] = True
                return True

            return False

        except Exception as e:
            print(f"检查轮次完成状态失败: {str(e)}")
            return False

    def get_round_completion_status(self, round_name: str) -> Dict:
        """获取轮次完成状态信息"""
        state = self.get_tournament_state()
        if not state:
            return {'completed': False, 'can_advance': False, 'next_round': None}

        try:
            # 检查当前轮次是否完成
            completed = self.can_advance_to_next_round(round_name)

            # 获取下一轮次
            next_round = self.get_next_round(round_name) if completed else None

            return {
                'completed': completed,
                'can_advance': completed,
                'next_round': next_round,
                'current_round': round_name
            }

        except Exception as e:
            print(f"获取轮次状态失败: {str(e)}")
            return {'completed': False, 'can_advance': False, 'next_round': None}

    def _auto_prepare_next_round(self, state: Dict, completed_round: str) -> bool:
        """自动准备下一轮（智能跳过不需要的复活赛）"""
        try:
            # 获取下一轮次（会自动跳过不需要的复活赛）
            next_round = self.get_next_round(completed_round)
            if not next_round or next_round == 'completed':
                return False

            # 获取下一轮配置
            next_round_config = self.get_round_config(next_round)
            if not next_round_config:
                return False

            # 检查是否可以开始下一轮
            validation_result = self._validate_round_switch(state, next_round, next_round_config)
            if not validation_result[0]:
                return False

            # 如果是复活赛，准备复活赛
            if next_round_config['type'] == 'revival':
                self._prepare_revival_round(state, next_round)

            # 不自动开启抽签，只是准备好数据结构
            # 管理员需要手动开启下一轮抽签

            return True

        except Exception as e:
            print(f"自动准备下一轮失败: {str(e)}")
            return False

    def can_advance_to_next_round(self, current_round: str) -> bool:
        """检查是否可以进入下一轮（动态版本）"""
        state = self.get_tournament_state()
        if not state:
            return False

        # 获取当前轮次配置
        round_config = self.get_round_config(current_round)
        if not round_config:
            return False

        # 检查当前轮次的所有比赛是否完成
        round_matches = [m for m in state['matches'] if m['round'] == current_round]
        expected_matches = round_config['groups_count']

        return len(round_matches) == expected_matches and all(m['completed'] for m in round_matches)

    def get_next_round(self, current_round: str) -> Optional[str]:
        """获取下一轮次名称（智能跳过不需要的复活赛）"""
        rounds = self.config['rounds']
        current_index = -1

        # 找到当前轮次的索引
        for i, round_config in enumerate(rounds):
            if round_config['name'] == current_round:
                current_index = i
                break

        if current_index == -1:
            return None

        # 查找下一个有效轮次
        for i in range(current_index + 1, len(rounds)):
            next_round_config = rounds[i]
            next_round_name = next_round_config['name']

            # 如果是复活赛，检查是否需要
            if next_round_config['type'] == 'revival':
                if self._should_skip_revival_round(current_round, next_round_name):
                    continue  # 跳过这个复活赛

            return next_round_name

        # 如果没有找到下一轮，说明比赛结束
        return 'completed'

    def _should_skip_revival_round(self, current_round: str, revival_round: str) -> bool:
        """判断是否应该跳过复活赛"""
        try:
            state = self.get_tournament_state()
            if not state:
                return True

            # 获取对应的主要轮次名称
            main_round_name = revival_round.replace('_revival', '_main')

            # 检查主要轮次是否存在且已完成
            main_round_config = self.get_round_config(main_round_name)
            if not main_round_config:
                return True  # 没有对应的主要轮次，跳过复活赛

            # 检查主要轮次是否完成
            if not self.can_advance_to_next_round(main_round_name):
                return True  # 主要轮次未完成，跳过复活赛

            # 检查是否有淘汰的队伍
            eliminated_teams = self._get_eliminated_teams(state, main_round_name)
            if len(eliminated_teams) == 0:
                return True  # 没有淘汰队伍，跳过复活赛

            # 获取复活赛配置，检查是否有复活名额
            revival_config = self.get_round_config(revival_round)
            if not revival_config or revival_config.get('advance_count', 0) == 0:
                return True  # 没有复活名额，跳过复活赛

            return False  # 需要进行复活赛

        except Exception as e:
            print(f"判断是否跳过复活赛失败: {str(e)}")
            return True  # 出错时跳过复活赛

    def advance_to_next_round_generic(self, current_round: str) -> Tuple[bool, Dict, str]:
        """通用的进入下一轮方法"""
        state = self.get_tournament_state()
        if not state:
            return False, {}, "获取比赛状态失败"

        try:
            # 检查是否可以进入下一轮
            if not self.can_advance_to_next_round(current_round):
                return False, {}, f"{current_round}轮次比赛尚未完成"

            # 获取下一轮次（会自动跳过不需要的复活赛）
            next_round = self.get_next_round(current_round)
            if not next_round:
                return False, {}, "无法确定下一轮次"

            if next_round == 'completed':
                # 比赛结束
                return self.complete_tournament()

            # 收集当前轮次的获胜者和失败者
            current_matches = [m for m in state['matches'] if m['round'] == current_round]
            winners = []
            losers = []

            for match in current_matches:
                if match['completed']:
                    if match['winner']:
                        winners.append(match['winner'])
                    if match['loser']:
                        losers.append(match['loser'])

            # 更新比赛状态
            state['current_round'] = next_round

            # 根据轮次类型更新相应的队伍列表（保持兼容性）
            next_round_config = self.get_round_config(next_round)
            if next_round_config:
                if next_round_config['type'] == 'revival':
                    # 复活赛：准备复活赛数据
                    self._prepare_revival_round(state, next_round)

                    # 更新旧数据结构（兼容性）
                    if current_round == self.config['rounds'][0]['name']:
                        state['round1_eliminated'] = losers
                        state['round1_advanced'] = winners
                else:
                    # 主要轮次，更新对应的队伍列表
                    round_teams_key = f"{next_round.replace('_main', '')}_teams"
                    state[round_teams_key] = winners

            if self.save_tournament_state(state):
                return True, state, f"成功进入{self.get_round_config(next_round)['display_name'] if self.get_round_config(next_round) else next_round}"
            else:
                return False, {}, "保存状态失败"

        except Exception as e:
            return False, {}, f"进入下一轮失败: {str(e)}"



    def draw_round1_revival(self) -> Tuple[bool, List[Dict], str]:
        """复活赛抽签"""
        state = self.get_tournament_state()
        if not state:
            return False, [], "获取比赛状态失败"

        if state['current_round'] != 'round1_main' or len(state['round1_eliminated']) != 5:
            return False, [], "复活赛条件不满足"

        try:
            eliminated_teams = state['round1_eliminated'].copy()
            random.shuffle(eliminated_teams)

            matches = []
            # 5队复活赛：1队轮空，4队两两对战
            if len(eliminated_teams) == 5:
                # 第一队轮空直接复活
                bye_team = eliminated_teams[0].copy()
                bye_team['status'] = 'revived'
                state['revival_teams'].append(bye_team)

                # 更新原队伍状态
                for team in state['teams']:
                    if team['id'] == bye_team['id']:
                        team['status'] = 'revived'
                        break

                # 其余4队两两对战
                for i in range(1, 5, 2):
                    match = self.create_match('round1_revival', eliminated_teams[i], eliminated_teams[i + 1])
                    matches.append(match)

            state['matches'].extend(matches)
            state['current_round'] = 'round1_revival'

            if self.save_tournament_state(state):
                return True, matches, "复活赛抽签完成"
            else:
                return False, [], "保存复活赛抽签结果失败"

        except Exception as e:
            return False, [], f"复活赛抽签失败: {str(e)}"

    def advance_to_round2(self) -> Tuple[bool, Dict, str]:
        """进入第二轮"""
        state = self.get_tournament_state()
        if not state:
            return False, {}, "获取比赛状态失败"

        try:
            # 收集复活赛获胜者
            revival_matches = [m for m in state['matches'] if m['round'] == 'round1_revival']
            for match in revival_matches:
                if match['completed'] and match['winner']:
                    match['winner']['status'] = 'revived'
                    if match['winner'] not in state['revival_teams']:
                        state['revival_teams'].append(match['winner'])

            # 第二轮参赛队伍：5个晋级队伍 + 3个复活队伍 = 8队
            round2_teams = state['round1_advanced'] + state['revival_teams']
            state['round2_teams'] = round2_teams
            state['current_round'] = 'round2_main'

            if self.save_tournament_state(state):
                return True, state, "成功进入第二轮"
            else:
                return False, {}, "保存第二轮状态失败"

        except Exception as e:
            return False, {}, f"进入第二轮失败: {str(e)}"

    def draw_round2_main(self) -> Tuple[bool, List[Dict], str]:
        """第二轮晋级赛抽签"""
        state = self.get_tournament_state()
        if not state:
            return False, [], "获取比赛状态失败"

        if state['current_round'] != 'round2_main':
            return False, [], "当前不是第二轮抽签阶段"

        try:
            advanced_teams = state['round1_advanced'].copy()
            revival_teams = state['revival_teams'].copy()

            # 抽签规则：复活队伍必须与晋级队伍对战
            random.shuffle(advanced_teams)
            random.shuffle(revival_teams)

            matches = []
            # 3个复活队伍与3个晋级队伍对战
            for i in range(min(len(revival_teams), len(advanced_teams))):
                match = self.create_match('round2_main', revival_teams[i], advanced_teams[i])
                matches.append(match)

            # 剩余的2个晋级队伍对战
            remaining_advanced = advanced_teams[len(revival_teams):]
            if len(remaining_advanced) >= 2:
                match = self.create_match('round2_main', remaining_advanced[0], remaining_advanced[1])
                matches.append(match)

            state['matches'].extend(matches)

            if self.save_tournament_state(state):
                return True, matches, "第二轮抽签完成"
            else:
                return False, [], "保存第二轮抽签结果失败"

        except Exception as e:
            return False, [], f"第二轮抽签失败: {str(e)}"

    def advance_to_round3(self) -> Tuple[bool, Dict, str]:
        """进入第三轮"""
        state = self.get_tournament_state()
        if not state:
            return False, {}, "获取比赛状态失败"

        try:
            # 收集第二轮获胜者
            round2_matches = [m for m in state['matches'] if m['round'] == 'round2_main']
            round3_teams = []

            for match in round2_matches:
                if match['completed'] and match['winner']:
                    round3_teams.append(match['winner'])

            if len(round3_teams) != 4:
                return False, {}, f"第二轮获胜队伍数量错误，应为4队，实际为{len(round3_teams)}队"

            state['round3_teams'] = round3_teams
            state['current_round'] = 'round3_main'

            if self.save_tournament_state(state):
                return True, state, "成功进入第三轮"
            else:
                return False, {}, "保存第三轮状态失败"

        except Exception as e:
            return False, {}, f"进入第三轮失败: {str(e)}"

    def draw_round3_main(self) -> Tuple[bool, List[Dict], str]:
        """第三轮晋级赛抽签"""
        state = self.get_tournament_state()
        if not state:
            return False, [], "获取比赛状态失败"

        if state['current_round'] != 'round3_main':
            return False, [], "当前不是第三轮抽签阶段"

        try:
            teams = state['round3_teams'].copy()
            random.shuffle(teams)

            matches = []
            # 4队分成2对进行比赛
            for i in range(0, len(teams), 2):
                if i + 1 < len(teams):
                    match = self.create_match('round3_main', teams[i], teams[i + 1])
                    matches.append(match)

            state['matches'].extend(matches)

            if self.save_tournament_state(state):
                return True, matches, "第三轮抽签完成"
            else:
                return False, [], "保存第三轮抽签结果失败"

        except Exception as e:
            return False, [], f"第三轮抽签失败: {str(e)}"

    def advance_to_final(self) -> Tuple[bool, Dict, str]:
        """进入决赛"""
        state = self.get_tournament_state()
        if not state:
            return False, {}, "获取比赛状态失败"

        try:
            # 收集第三轮获胜者
            round3_matches = [m for m in state['matches'] if m['round'] == 'round3_main']
            final_teams = []

            for match in round3_matches:
                if match['completed'] and match['winner']:
                    final_teams.append(match['winner'])

            if len(final_teams) != 2:
                return False, {}, f"第三轮获胜队伍数量错误，应为2队，实际为{len(final_teams)}队"

            state['final_teams'] = final_teams
            state['current_round'] = 'final'
            state['draw_enabled'] = False  # 决赛不需要抽签

            # 自动创建决赛比赛
            final_match = self.create_match('final', final_teams[0], final_teams[1])
            state['matches'].append(final_match)

            # 更新队伍状态为已配对
            for team in final_teams:
                for original_team in state['teams']:
                    if original_team['id'] == team['id']:
                        original_team['status'] = 'final_paired'
                        break

            if self.save_tournament_state(state):
                return True, state, "成功进入决赛，比赛已自动配对"
            else:
                return False, {}, "保存决赛状态失败"

        except Exception as e:
            return False, {}, f"进入决赛失败: {str(e)}"

    def draw_final(self) -> Tuple[bool, List[Dict], str]:
        """决赛抽签"""
        state = self.get_tournament_state()
        if not state:
            return False, [], "获取比赛状态失败"

        if state['current_round'] != 'final':
            return False, [], "当前不是决赛阶段"

        try:
            teams = state['final_teams'].copy()

            # 决赛只有一场比赛
            if len(teams) == 2:
                match = self.create_match('final', teams[0], teams[1])
                state['matches'].append(match)

                if self.save_tournament_state(state):
                    return True, [match], "决赛对阵确定"
                else:
                    return False, [], "保存决赛对阵失败"
            else:
                return False, [], f"决赛队伍数量错误，应为2队，实际为{len(teams)}队"

        except Exception as e:
            return False, [], f"决赛抽签失败: {str(e)}"

    def complete_tournament(self) -> Tuple[bool, Dict, str]:
        """完成比赛"""
        state = self.get_tournament_state()
        if not state:
            return False, {}, "获取比赛状态失败"

        try:
            # 获取决赛结果
            final_matches = [m for m in state['matches'] if m['round'] == 'final']
            if len(final_matches) != 1 or not final_matches[0]['completed']:
                return False, {}, "决赛尚未完成"

            final_match = final_matches[0]
            state['champion'] = final_match['winner']
            state['runner_up'] = final_match['loser']
            state['current_round'] = 'completed'

            # 更新冠亚军状态
            for team in state['teams']:
                if team['id'] == state['champion']['id']:
                    team['status'] = 'champion'
                elif team['id'] == state['runner_up']['id']:
                    team['status'] = 'runner_up'

            if self.save_tournament_state(state):
                return True, state, "比赛圆满结束"
            else:
                return False, {}, "保存比赛结果失败"

        except Exception as e:
            return False, {}, f"完成比赛失败: {str(e)}"

    def reset_tournament(self) -> bool:
        """重置比赛"""
        if self.redis_client:
            try:
                self.redis_client.delete(self.tournament_key)
                return True
            except Exception as e:
                print(f"重置比赛失败: {e}")
        return False
